﻿using System;
using System.Windows;
using System.Windows.Controls;

using Microsoft.Devices.Sensors;

namespace Coding4Fun.Cannon.TechEdPhone.Complete.Controls
{
    public class AccelerometerUserControl : UserControl
    {
        AccelerometerSensor Accelerometer { get; set; }

        public AccelerometerUserControl()
        {
	        Accelerometer = new AccelerometerSensor();
	        Accelerometer.ReadingChanged += Accelerometer_ReadingChanged;
            
        }

        void Accelerometer_ReadingChanged(object sender, AccelerometerReadingAsyncEventArgs e)
        {
	        if (ReadingFilter())
	        {
		        Dispatcher.BeginInvoke(() => AccelerometerReadingChanged(e.Value));
	        }
        }


        public new Visibility Visibility
        {
	        get { return base.Visibility; }
	        set
	        {
		        base.Visibility = value;
		        try
		        {
			        if (Accelerometer.State == SensorState.Ready)
			        {
				        if (value == Visibility.Visible)
					        Accelerometer.Start();
				        else
					        Accelerometer.Stop();
			        }
		        }
		        catch (Exception) { }
	        }
        }

		public virtual void AccelerometerReadingChanged(SensorData<AccelerometerReading> data)
		{ }

		const int ReadingsToIgnore = 5;
		int _counter = 0;

		bool ReadingFilter()
		{
			if (_counter >= ReadingsToIgnore)
			{
				_counter = 0;
				return true;
			}

			_counter++;
			return false;
		}

    }
}
